import React from 'react';
import * as echarts from 'echarts';
import { useSize } from 'ahooks';

export default ({
  option = null,
  startIndex = 0,
  pageSize = 0,
  hoverColIndex = 0,
  onChangeHoverColIndex = () => {},
}) => {
  const chartRef = React.useRef(null);
  const chartSize = useSize(chartRef);
  const chartIns = () =>
    echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
  const chartResize = () => {
    setTimeout(() => {
      chartIns()?.resize();
    }, 500);
  };

  React.useEffect(() => {
    const _chartIns = chartIns();
    _chartIns.on('highlight', (v) => {
      let i = v?.batch?.[0]?.dataIndex;
      if (typeof i === 'undefined') return;
      onChangeHoverColIndex(i);
    });
    _chartIns.on('mouseout', () => {
      onChangeHoverColIndex(-1);
    });
    return () => {
      _chartIns?.dispose();
    };
  }, []);

  React.useEffect(() => {
    chartResize();
  }, [chartSize]);

  React.useEffect(() => {
    if (!option) return;
    chartIns()?.setOption(
      {
        ...option,
        dataZoom: {
          startValue: startIndex,
          endValue: startIndex + pageSize - 1,
          type: 'inside',
          zoomOnMouseWheel: false,
          moveOnMouseMove: false,
          moveOnMouseWheel: false,
          preventDefaultMouseMove: false,
          throttle: 0,
        },
      },
      true,
    );
  }, [JSON.stringify(option), startIndex, pageSize]);

  React.useEffect(() => {
    chartIns()?.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: hoverColIndex,
    });
  }, [hoverColIndex]);

  return <div ref={chartRef} style={{ width: '100%', height: '100%' }} />;
};
